package com.hcmus.post2server;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import common.Promotion;
import common.PromotionImage;
import common.Store;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import config.config;
import config.column_name_define;

import android.util.Config;
import android.util.Log;

public class post2server {
	
	
	
	public static String postRecive(/*String endpoint, */Map<String, String> params)
            throws IOException {   	
        
        URL url;
        String endpoint = "";
        if(config.getDataServer_v1 == true){
        	endpoint = config.SERVER_URL_POST_v1;
        }else{
        	endpoint = config.SERVER_URL_POST;
        }
        try {
            url = new URL(endpoint);
        } catch (MalformedURLException e) {
            throw new IllegalArgumentException("invalid url: " + endpoint);
        }
        StringBuilder bodyBuilder = new StringBuilder();
        Iterator<Entry<String, String>> iterator = params.entrySet().iterator();
        // constructs the POST body using the parameters
        while (iterator.hasNext()) {
            Entry<String, String> param = iterator.next();
            bodyBuilder.append(param.getKey()).append('=')
                    .append(param.getValue());
            if (iterator.hasNext()) {
                bodyBuilder.append('&');
            }
        }
        String body = bodyBuilder.toString();
        //Log.v(TAG, "Posting '" + body + "' to " + url);
        byte[] bytes = body.getBytes();
        HttpURLConnection conn = null;
        String result="";
        try {
        	Log.e("URL", "> " + url);
            conn = (HttpURLConnection) url.openConnection();
            conn.setDoOutput(true);
            conn.setUseCaches(false);
            conn.setFixedLengthStreamingMode(bytes.length);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type",
                    "application/x-www-form-urlencoded;charset=UTF-8");
            // post the request
            try{
            OutputStream out = conn.getOutputStream();
            out.write(bytes);
            out.close();
            }catch(Exception ex){
            	System.out.println("er: " + ex.toString());
            }
            // handle the response
            int status = conn.getResponseCode();
            String re = conn.getResponseMessage();
            BufferedReader rd = null;           
            String line;
            rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); 
            while ((line = rd.readLine()) != null) { 
            	result += line ; 
             } 
           
            if (status != 200) {
              throw new IOException("Post failed with error code " + status);
            }
            return result;
            
        } finally {
            if (conn != null) {
                conn.disconnect();
                return result;
            }
        }
      }
	
	public static String postRecive(String endpoint, Map<String, String> params)
            throws IOException {   	
        
        URL url;       
        try {
            url = new URL(endpoint);
        } catch (MalformedURLException e) {
            throw new IllegalArgumentException("invalid url: " + endpoint);
        }
        StringBuilder bodyBuilder = new StringBuilder();
        Iterator<Entry<String, String>> iterator = params.entrySet().iterator();
        // constructs the POST body using the parameters
        while (iterator.hasNext()) {
            Entry<String, String> param = iterator.next();
            bodyBuilder.append(param.getKey()).append('=')
                    .append(param.getValue());
            if (iterator.hasNext()) {
                bodyBuilder.append('&');
            }
        }
        String body = bodyBuilder.toString();
        //Log.v(TAG, "Posting '" + body + "' to " + url);
        byte[] bytes = body.getBytes();
        HttpURLConnection conn = null;
        String result="";
        try {
        	Log.e("URL", "> " + url);
            conn = (HttpURLConnection) url.openConnection();
            conn.setDoOutput(true);
            conn.setUseCaches(false);
            conn.setFixedLengthStreamingMode(bytes.length);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type",
                    "application/x-www-form-urlencoded;charset=UTF-8");
            // post the request
            try{
            OutputStream out = conn.getOutputStream();
            out.write(bytes);
            out.close();
            }catch(Exception ex){
            	System.out.println("er: " + ex.toString());
            }
            // handle the response
            int status = conn.getResponseCode();
            String re = conn.getResponseMessage();
            BufferedReader rd = null;           
            String line;
            rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); 
            while ((line = rd.readLine()) != null) { 
            	result += line ; 
             } 
           
            if (status != 200) {
              throw new IOException("Post failed with error code " + status);
            }
            return result;
            
        } finally {
            if (conn != null) {
                conn.disconnect();
                return result;
            }
        }
      }
	
	public static JSONObject postReciveJson(String endpoint, Map<String, String> params)
            throws IOException {   	
        
        URL url;    
        JSONObject jsonObj = null;
        try {
            url = new URL(endpoint);
        } catch (MalformedURLException e) {
            throw new IllegalArgumentException("invalid url: " + endpoint);
        }
        StringBuilder bodyBuilder = new StringBuilder();
        Iterator<Entry<String, String>> iterator = params.entrySet().iterator();
        // constructs the POST body using the parameters
        while (iterator.hasNext()) {
            Entry<String, String> param = iterator.next();
            bodyBuilder.append(param.getKey()).append('=')
                    .append(param.getValue());
            if (iterator.hasNext()) {
                bodyBuilder.append('&');
            }
        }
        String body = bodyBuilder.toString();
        //Log.v(TAG, "Posting '" + body + "' to " + url);
        byte[] bytes = body.getBytes();
        HttpURLConnection conn = null;
        String json="";
        try {
        	Log.e("URL", "> " + url);
            conn = (HttpURLConnection) url.openConnection();
            conn.setDoOutput(true);
            conn.setUseCaches(false);
            conn.setFixedLengthStreamingMode(bytes.length);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type",
                    "application/x-www-form-urlencoded;charset=UTF-8");
            // post the request
            try{
            OutputStream out = conn.getOutputStream();
            out.write(bytes);
            out.close();
            }catch(Exception ex){
            	System.out.println("er: " + ex.toString());
            }
            // handle the response
            int status = conn.getResponseCode();
            String re = conn.getResponseMessage();
            BufferedReader rd = null;           
            String line = null;
            StringBuilder sb = new StringBuilder();
            rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));            
            while ((line = rd.readLine()) != null) { 
            	sb.append(line + "\n");
             } 
            json = sb.toString();
            if (status != 200) {
              throw new IOException("Post failed with error code " + status);
            }
            
            try {
    			jsonObj = new JSONObject(json);
    		} catch (JSONException e) {
    			Log.e("JSON Parser", "Error parsing data " + e.toString());
    		}
            return jsonObj;
            
        } finally {
            if (conn != null) {
                conn.disconnect();
                return jsonObj;
            }
        }
      }
	
	public static ArrayList<Store> parseJSONStore(JSONObject json){
		ArrayList<Store> resultData = new ArrayList<Store>();
		JSONArray listStore;
		try {
			listStore = json.getJSONArray("stores");
			for(int i = 0 ; i < listStore.length() ; i++){
				JSONObject item = listStore.getJSONObject(i);
				resultData.add(new Store(Integer.valueOf(item.getString(column_name_define.STORE_ID)),
										 item.getString(column_name_define.STORE_NAME), 
										 Integer.valueOf(item.getString(column_name_define.STORE_TYPE)), 
										 "", 
										 item.getString(column_name_define.STORE_PHONE), 
										 item.getString(column_name_define.STORE_LATITUDE), 
										 item.getString(column_name_define.STORE_LONGITUDE), 
										 item.getString(column_name_define.STORE_ALTITUDE), 
										 Integer.valueOf(item.getString(column_name_define.STORE_PROVINCE_ID)), 
										 item.getString(column_name_define.STORE_PROVINCE_NAME), 
										 Integer.valueOf(item.getString(column_name_define.STORE_DISTRICT_ID)), 
										 item.getString(column_name_define.STORE_DISTRICT_NAME), 
										 item.getString(column_name_define.STORE_WARD), 
										 item.getString(column_name_define.STORE_STREET), 
										 item.getString(column_name_define.STORE_HOUSE_NUMBER), 
										 Integer.valueOf(item.getString(column_name_define.STORE_VOTE)), 
										 item.getString(column_name_define.STORE_DESCRIPTION), 
										 Integer.valueOf(item.getString(column_name_define.STORE_CUSTOMER_ID)), 
										 Integer.valueOf(item.getString(column_name_define.STORE_CHAIN_STORE_ID)),
										 item.getString(column_name_define.STORE_HOUSE_NUMBER) 
										 + " " + item.getString(column_name_define.STORE_STREET)
										 + " " + item.getString(column_name_define.STORE_WARD)
										 + " " + item.getString(column_name_define.STORE_DISTRICT_NAME)
										 + " " + item.getString(column_name_define.STORE_PROVINCE_NAME)
										)
							);
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return resultData;
	}
	
	
	public static ArrayList<Promotion> parseJSONPromotion(JSONObject json){
		ArrayList<Promotion> resultData = new ArrayList<Promotion>();
		JSONArray listPromotion;
		try {
			listPromotion = json.getJSONArray("promotions");
			for(int i = 0 ; i < listPromotion.length() ; i++){
				JSONObject item = listPromotion.getJSONObject(i);
				resultData.add(new Promotion(Integer.valueOf(item.getString(column_name_define.PROMOTION_ID)),
											 item.getString(column_name_define.PROMOTION_NAME), 
											 Integer.valueOf(item.getString(column_name_define.PROMOTION_STORE_ID)), 
											 item.getString(column_name_define.PROMOTION_OLD_PRICE), 
											 item.getString(column_name_define.PROMOTION_DECREASE_PRICE), 
											 item.getString(column_name_define.PROMOTION_PERCENT), 
											 Integer.valueOf(item.getString(column_name_define.PROMOTION_FROM_DATE)), 
											 Integer.valueOf(item.getString(column_name_define.PROMOTION_TO_DATE)), 
											 Integer.valueOf(item.getString(column_name_define.PROMOTION_QUANTITY)), 
											 item.getString(column_name_define.PROMOTION_DESCRIPTION)
											)
							);
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return resultData;
	}
}
